package com.cloudptt.api.product;

import com.cloudptt.api.comm.CauseCont;
import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.models.lbs.ReportData;
import com.cloudptt.api.models.lbs.VitalData;
import com.cloudptt.api.pjsip.api.SipManager;
import com.cloudptt.api.product.func.lbs.AlarmTimer;
import com.cloudptt.api.product.func.lbs.IAlarmTimeout;
import com.cloudptt.api.product.func.lbs.IKeepLive;
import com.cloudptt.api.product.func.lbs.LbsListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.LBSOperator;
import com.mcptt.config.local.SysConfig;
import com.mcptt.db.op.MapDbOperator;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class ReportAndKeepLive extends BroadcastReceiver implements IAlarmTimeout {
	private final static String THIS_FILE = "ReportAndKeepLive";
	private final static String Gis_Url = "/map/ias/ue-gas-gis";
	
	public final static String TimerOutKey_Clear = "clearData";
	public final static String TimerOutKey_Report = "reportData";
	
	private static long BaseDate = 0;
	private static int curHeartRate = 999;

	private Context ctx = null;
	private LBSOperator operator;
	private MapDbOperator dpOperator = null;
	private LbsListener listener = null;
	private INewReport newReport = null;
	
	private AlarmTimer reportTimer = null;
//	private AlarmTimer keepLiveTimer = null;
	private IGetReportData reportDate = null;
//	private IKeepLive keepLive = null;
	private volatile boolean isRecvDistribute = false;
	private volatile boolean isStartTimer = false;


	public ReportAndKeepLive(Context ctx,LBSOperator operator,MapDbOperator dpOperator,IGetReportData reportDate) {
		this.ctx = ctx;
//		Gis_Url = "http://" + gisSvr + Gis_Url;
//		Gis_Url = "http://" + "47.117.130.92" + Gis_Url;
		this.operator = operator;
		this.dpOperator = dpOperator;
		this.reportDate = reportDate;
//		this.keepLive = keepLive;
		BaseDate = System.currentTimeMillis();
		Log.d(THIS_FILE, "ReportAndKeepLive Gis_Url = "+Gis_Url);
		
		ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_REGISTER_TIMEOUT));
		ctx.registerReceiver(this, new IntentFilter(SipManager.ACTION_SIP_MESSAGE_Distribute));
	}

	public void setListener(LbsListener listener) {
		this.listener = listener;
	}
	
	public void setNewReport(INewReport newReport)
	{
		Log.d(THIS_FILE, "setNewReport");
		this.newReport = newReport;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.d(THIS_FILE, "onReceive:Action is " + action);
		if (SipManager.ACTION_SIP_REGISTER_TIMEOUT.equals(action)) 
		{
			doTimerOutClear();
		}
		else if (SipManager.ACTION_SIP_MESSAGE_Distribute.equals(action)) 
		{
//			String infoXml = intent.getStringExtra(SipManager.INFO_XML);
//			Log.d(THIS_FILE, "onReceive: ACTION_SIP_MESSAGE_LOCATION infoXml = " + infoXml);
			String locationXml = intent.getStringExtra(SipManager.LOCATION_XML);
			Log.i(THIS_FILE, "onReceive: ACTION_SIP_MESSAGE_Distribute locationXml = " + locationXml);
			int msgType = intent.getIntExtra(SipManager.MSG_TYPE, -1);
			try
			{
//				if(msgType == LocationInfoBody.Type_Distribute)
//				{
////					Log.i(THIS_FILE, "onReceive: LocationInfoBody.Type_Distribute");
////					IInfoBody_NewCall infoBody = McpttInfoBody_NewCall.parseXmlStr(infoXml);
//					if(locationXml != null
//							&& locationXml.length() > 0)
//					{
//						LocationInfoBody_Distribute  body = LocationInfoBody_Distribute.parseXmlStr(locationXml);
//						
//						Log.i(LBSFunc.Log_Key, "body = "+body.toString());
//						
//						if(body != null
//								&& body.getDataList() != null)
//						{
//							List<ReportData> dataList = body.getDataList();
//							this.dpOperator.cleanAllLogin();
//							for(Iterator<ReportData> itor = dataList.iterator();itor.hasNext();)
//							{
//								ReportData data = itor.next();
//								Log.i(THIS_FILE, "onReceive: LocationInfoBody.Type_Report data = " + data);
//								long time = data.getDate();
//								String mcpttId = data.getNum();
//								LocationData locData = data.getLocData();
//								Log.i(THIS_FILE, "onReceive: LocationInfoBody.Type_Report mcpttId = " + mcpttId);
//								Log.i(THIS_FILE, "onReceive: LocationInfoBody.Type_Report locData = " + locData);
//								if(mcpttId != null
//										&& data != null)
//								{
//									MapPointInfo point = new MapPointInfo(mcpttId,MapPointInfo.MapPointType_GPS,time,locData,"");
//									Log.i(THIS_FILE, "onReceive: LocationInfoBody.Type_Report point = " + point);
//									this.dpOperator.insertOrUptNewPoint(point);
//									isRecvDistribute = true;
//									
//									if(keepLive != null)
//									{
//										keepLive.keepLive(true);
//									}
//								}
//							}
//						}
//
//						if(listener != null)
//						{
//							listener.recvNewReport();
//						}
//						
//					}
//
//				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}

	}

	public void startTimer(int gisInterval) {
		Log.d(THIS_FILE, "startTimer");
		if(!isStartTimer)
		{
			stopTimer();
			doReportDate();
			this.reportTimer = new AlarmTimer(ctx,TimerOutKey_Report,gisInterval,this);
			reportTimer.startRefreshTimer();
		
//			this.keepLiveTimer = new AlarmTimer(ctx,TimerOutKey_Clear,20,this);
//			keepLiveTimer.startRefreshTimer();
			
			isStartTimer = true;
		}
	}
	public void stopTimer() {
		Log.d(THIS_FILE, "stopTimer");
//		if(keepLiveTimer != null)
//		{
//			this.keepLiveTimer.stopRefreshTimer();
//			this.keepLiveTimer = null;
//		}
		if(reportTimer != null)
		{
			this.reportTimer.stopRefreshTimer();
			this.reportTimer = null;
		}
		isStartTimer = false;
	}
	
	public void clearResource() {
		Log.d(THIS_FILE, "LBSBroadcast clearResource");
//		if(keepLiveTimer != null)
//		{
//			this.keepLiveTimer.stopRefreshTimer();
//			this.keepLiveTimer = null;
//		}
		if(reportTimer != null)
		{
			this.reportTimer.stopRefreshTimer();
			this.reportTimer = null;
		}
		this.ctx.unregisterReceiver(this);
		this.ctx = null;
		this.listener = null;
	}

	@Override
	public void timeIntervalTimeout(String alarmAction) {
		// TODO Auto-generated method stub
		Log.d(THIS_FILE, "timeIntervalTimeout alarmAction = " + alarmAction);
		if(TimerOutKey_Clear.equals(alarmAction))
		{
			doReportDate();
			doTimerOutClear();
		}
		else if(TimerOutKey_Report.equals(alarmAction))
		{
			doReportDate();
		}
	}
	
	private void doTimerOutClear()
	{
		Log.i(THIS_FILE, "doTimerOutClear isRecvLbsDistribute = " + isRecvDistribute);
		if(!isRecvDistribute)
		{
			this.dpOperator.cleanAllLogin();
			
			if(listener != null)
			{
				listener.recvNewReport();
			}
//			if(keepLive != null)
//			{
//				keepLive.keepLive(false);
//			}
		}
		isRecvDistribute = false;
	}
	public void doReportDate()
	{
		if(operator != null)
		{
			int result = CauseCont.OperateErr_Exception;

			ReportData data = reportDate.getReportData();
			String url = SysConfig.getGisServerInfo().getHttpUrl() + Gis_Url;
//
			result = operator.reportLocation(url,data);
			if(result != CauseCont.OperateCheck_Suc)
			{
				String errStr = CauseCont.getOperateCheckErrStr(result,ctx);
				CommDlg.showToast(ctx,errStr);
			}
			if(newReport != null)
			{
				Log.i(THIS_FILE, "doReportDate newReport data = " + data);
				newReport.newReport(data);
			}
		}
	}
	
	public VitalData getCurVitalData() {
		// TODO Auto-generated method stub
		long curTime = System.currentTimeMillis();
		int val = (int)(curTime - BaseDate) /1000;
		return new VitalData(val,curHeartRate,"23",80,"000");
	}

}
